from sqlalchemy.orm import Session
from datetime import datetime
from app import models, schemas
from typing import List, Optional

class ScanResultRepository:
    @staticmethod
    async def create_scan_result(db: Session, scan_result: schemas.ScanResultCreate) -> models.ScanResult:
        db_scan_result = models.ScanResult(**scan_result.dict())
        db.add(db_scan_result)
        db.commit()
        db.refresh(db_scan_result)
        return db_scan_result

    @staticmethod
    async def create_scan_results(db: Session, scan_results: List[schemas.ScanResultCreate]) -> List[models.ScanResult]:
        db_scan_results = [models.ScanResult(**result.dict()) for result in scan_results]
        db.add_all(db_scan_results)
        db.commit()
        for result in db_scan_results:
            db.refresh(result)
        return db_scan_results

    @staticmethod
    async def get_scan_results(
        db: Session, 
        skip: int = 0, 
        limit: int = 100,
        status: Optional[str] = None
    ) -> List[models.ScanResult]:
        query = db.query(models.ScanResult)
        if status:
            query = query.filter(models.ScanResult.status == status)
        return query.offset(skip).limit(limit).all()

    @staticmethod
    async def get_scan_result(db: Session, result_id: int) -> Optional[models.ScanResult]:
        return db.query(models.ScanResult).filter(models.ScanResult.id == result_id).first()

    @staticmethod
    async def update_scan_result_status(
        db: Session, 
        result_id: int, 
        status: str,
        action_time: datetime = None
    ) -> Optional[models.ScanResult]:
        db_result = db.query(models.ScanResult).filter(models.ScanResult.id == result_id).first()
        if db_result:
            db_result.status = status
            if action_time:
                db_result.action_time = action_time
            db.commit()
            db.refresh(db_result)
        return db_result

    @staticmethod
    async def delete_all_results(db: Session) -> int:
        """删除所有扫描结果"""
        deleted = db.query(models.ScanResult).delete()
        db.commit()
        return deleted

    @staticmethod
    async def delete_old_results(db: Session, before_date: datetime) -> int:
        """删除指定日期之前的扫描结果"""
        deleted = db.query(models.ScanResult).filter(
            models.ScanResult.scan_time < before_date
        ).delete()
        db.commit()
        return deleted
